package com.wxx;

/**
 * @author: Jetwang
 * @date: 2022/3/28 21:46
 * @description: LoopQueue 循环队列
 * @version: 1.0
 */
public class LoopQueue<T> implements Queue<T> {
    private T[] data;
    private int front, tail;
    private int size;

    public LoopQueue(int capacity) {
        // 循环队列需要浪费一个位置，所以容量需要加一
        data = (T[])new Object[capacity + 1];
        // 初始时，front，tail都为0
        front = 0;
        tail = 0;
        size = 0;
    }

    public LoopQueue() {
        // 默认初始容量为10
        this(10);
    }

    /**
     * 获取容量大小
     * @return
     */
    public int getCapacity() {
        return data.length - 1;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return front == tail;
    }

    @Override
    public void enqueue(T t) {
        // 判断队列是否已满
        if ((tail+1) % data.length == front) {
            // 扩容
            resize(getCapacity() * 2);
        }
        data[tail] = t;
        // 尾部移动
        tail = (tail + 1) % data.length;
        size++;
    }

    /**
     * 扩容队列
     * @param newCapacity
     */
    private void resize(int newCapacity) {
        T[] newDate = (T[])new Object[newCapacity + 1];
        for (int i = 0; i < size; i++) {
            // front也可能循环越界，需进行取余
            newDate[i] = data[(front + i) % data.length];
        }
        data = newDate;
        front = 0;
        tail = size;
    }

    @Override
    public T dequeue() {
        // 判断队列是否为空
        if (isEmpty()) {
            throw new IllegalArgumentException("Cannot dequeue from an empty queue");
        }
        T t = data[front];
        data[front] = null;
        // 头部移动
        front = (front + 1) % data.length;
        size--;
        if (size == getCapacity() / 4 && getCapacity() / 2 != 0) {
            // 缩容
            resize(getCapacity() / 2);
        }
        return t;
    }

    @Override
    public T getFront() {
        // 判断队列是否为空
        if (isEmpty()) {
            throw new IllegalArgumentException("queue is empty");
        }
        return data[front];
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("LoopQueue:");
        builder.append("front [");
        for (int i = front; i != tail; i = (i + 1) % data.length) {
            builder.append(data[i]);
            if ((i + 1) % data.length != tail) {
                builder.append(",");
            }
        }
        builder.append("] tail");
        return builder.toString();
    }
}
